﻿#region

using MiniExcelLibs;

#endregion

namespace Vin.Extension.Excel;

public class ExcelHelper
{
    /// <summary>
    /// 读取Excel
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="sheetName">Sheet 名称</param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static List<T> ReadExcel<T>(Stream stream, string? sheetName = null) where T : class, new()
    {
        return stream.Query<T>(sheetName).ToList();
    }

    /// <summary>
    /// 保存Excel
    /// </summary>
    /// <param name="list"></param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static Stream SaveExcel<T>(List<T> list) where T : class, new()
    {
        var memoryStream = new MemoryStream();
        memoryStream.SaveAs(list);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return memoryStream;
    }

    /// <summary>
    /// 保存Excel
    /// </summary>
    /// <param name="list"></param>
    /// <param name="fileName"></param>
    /// <typeparam name="T"></typeparam>
    public static void SaveExcel<T>(List<T> list, string fileName) where T : class, new()
    {
        MiniExcel.SaveAs(fileName, list);
    }

    /// <summary>
    /// Excel 转换为字节数组
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    public static async Task<byte[]> ToBytes(object? list, IConfiguration? configuration = null)
    {
        using var stream = new MemoryStream();
        await stream.SaveAsAsync(list, configuration: configuration);
        return stream.ToArray();
    }
}